//
//  ViewController.m
//  组播发送
//
//  Created by lenkeng on 2019/9/16.
//  Copyright © 2019 lenkeng. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncUdpSocket.h"
#import "UIView+Toast.h"
#import "SCIPAddress.h"

@interface ViewController ()<GCDAsyncUdpSocketDelegate>
@property (nonatomic, strong)GCDAsyncUdpSocket* udp_sock;
@property (nonatomic, strong)NSTimer* timer;
@property (nonatomic, strong)NSString* log;
@property (nonatomic, strong)UITextView* textView;

@end

@implementation ViewController

- (void)beginUDP {

    NSString *message = @"me_123456";
    [_udp_sock sendData:[message dataUsingEncoding:NSUTF8StringEncoding] toHost:@"239.255.42.43"  port:8100 withTimeout:-1 tag:0];
    _textView.text = [[_textView.text stringByAppendingString:message] stringByAppendingString:@"\n"];
    
}


-(void)loadData{
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    //    [webView loadRequest:request];
    
    NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data,NSError *connectionError) {
        // 需要将二进制数据转换成html的字符串
        // 注：NSData转为字符串没有类方法
        // ENCODING字符编码,如果没有特殊要求,在iOS中统一使用UTF8
        NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", html);
        
        //用webView加载html
        /**
         baseURL:http://www.baidu.com
         使用的时候URL就可以只传后半部分就行
         */
        
        
    }];
    
}

- (void)createClientUDPSocket {
    _udp_sock = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    NSError* bindError = nil;
    [_udp_sock bindToPort:8100 error:&bindError];
    if (bindError) {
        NSLog(@"error:%@", bindError);
    }
    
    NSError* error = nil;
    [_udp_sock enableBroadcast:YES error:&error];
    if (error) {
        NSLog(@"error:%@", error);
    }
    
    NSError* mError = nil;
    [_udp_sock joinMulticastGroup:@"239.255.42.43" error:&mError];
    if (mError) {
        NSLog(@"mError:%@", mError);
    }
    
    NSError* receiveError = nil;
    [_udp_sock beginReceiving:&receiveError];
    if (receiveError) {
        NSLog(@"receiveError:%@", receiveError);
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadData];
    [self createClientUDPSocket];
    __weak typeof(self) weak_self = self;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _timer = [NSTimer timerWithTimeInterval:3.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [weak_self beginUDP];
            NSLog(@"开始UDP");
        }];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    });
   
    
    _textView = [[UITextView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_textView];
    _textView.font = [UIFont systemFontOfSize:20];
    
    
//    [self createUDPServer];

    // Do any additional setup after loading the view.
}

-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSString *host = nil;
    uint16_t port = 0;
    [GCDAsyncUdpSocket getHost:&host port:&port fromAddress:address];

    NSString* dataString = [NSString stringWithFormat:@"ReceiveData = %@, fromAddress = %@, Port:%d",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding],host, port];//从此可以获取服务端回应的ip和端口 用于后面的tcp连接NSLog(@"Adress = %@ %i",host,port];
//    [self.view makeToast:[NSString stringWithFormat:dataString]];
    _textView.text = [[_textView.text stringByAppendingString:dataString] stringByAppendingString:@"\n"];

    
}


@end
